package webIO.download;

import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;


public class ExcelDownload {

    /**
     * 下载Excel
     *
     * @param response
     * @param fileName 文件名
     * @param wb       excel
     * @throws IOException
     */
    public static void responseOutputExcel(HttpServletResponse response, String fileName, Workbook wb) throws IOException {
        response.setHeader("Content-disposition", "attachment;filename=" +
                new String(fileName.getBytes(), StandardCharsets.ISO_8859_1) + ".xlsx");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.flushBuffer();

        OutputStream outputStream = response.getOutputStream();
        wb.write(outputStream);
        wb.close();
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 生成Workbook
     *
     * @param sheetName
     * @param statBodyList
     * @param statTypeList
     * @return
     */
    private Workbook generateWorkbook(String sheetName, List<StatBody> statBodyList, List<Integer> statTypeList) {
        Workbook workbook = new SXSSFWorkbook();
        SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet(sheetName);

        if (CollectionUtils.isEmpty(statBodyList)) {
            log.info("导出Excel数据为空");
            return workbook;
        }

        final int cellWidth = 4788;
        List<Integer> cellWidthList = Lists.newArrayList(CommonConstants.EXCEL_WIDTH.USERNAME, cellWidth);
        List<String> headTitleList = Lists.newArrayList("调查人员", "调查管理人员");
        statTypeList.forEach(type -> {
            String desc = DashboardStatTypeEnum.valueOf(type).getDesc();
            headTitleList.add(desc);//列头
            cellWidthList.add(cellWidth);//列宽
        });
        String[] columnTitles = headTitleList.toArray(String[]::new);

        //设置列宽
        this.setSheetColsWidth(sheet, cellWidthList.stream().mapToInt(Integer::intValue).toArray());

        // 表头样式
        XSSFFont headFont = (XSSFFont) workbook.createFont();
        headFont.setBold(true);
        headFont.setFontName("微软雅黑");
        headFont.setFontHeightInPoints(XSSFFont.DEFAULT_FONT_SIZE);//font_size
        CellStyle headCellStyle = workbook.createCellStyle();
        headCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        headCellStyle.setFont(headFont);

        // 冻结窗格、内容筛选、表格保护
        sheet.createFreezePane(2, 1);
        sheet.setAutoFilter(CellRangeAddress.valueOf("B1"));
        sheet.lockAutoFilter(false);
        sheet.protectSheet("cg");

        int rowNum= 0;
        SXSSFRow head = sheet.createRow(rowNum++);
        head.setHeightInPoints(25);//cell_height
        for (int i = 0; i < columnTitles.length; i++) {
            Cell cell = head.createCell(i);
            cell.setCellValue(columnTitles[i]);
            cell.setCellStyle(headCellStyle);
        }

        for (StatBody statBody : statBodyList) {
            SXSSFRow row = sheet.createRow(rowNum++);
            int cellIdx = 0;
            row.createCell(cellIdx++).setCellValue(statBody.getUsername());
            row.createCell(cellIdx++).setCellValue(statBody.getSuperName());
            Map<Integer, Number> dataMap = statBody.getDataMap();
            for (Integer type : statTypeList) {
                Number number = dataMap.get(type);
                row.createCell(cellIdx++).setCellValue(String.valueOf(number));
            }
        }

        return workbook;
    }

    /**
     * 设置列宽
     *
     * @param sheet
     * @param colWidths
     */
    public static void setSheetColsWidth(Sheet sheet, int[] colWidths) {
        for (int i = 0; i < colWidths.length; i++) {
            sheet.setColumnWidth(i, colWidths[i]);
        }
    }

    /**
     * excel行数据实体类
     */
    @Data
    @Accessors(chain = true)
    public static class StatBody {
        private String username;
        private String superName;
        private Map<Integer, Number> dataMap;//动态列
    }
}
